package sc.digital.human;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Arrays;
import java.util.Objects;

public class Config {
    public static final Image LOGO = new ImageIcon(Objects.requireNonNull(Config.class.getResource("/logo.png"))).getImage();
    public static final String HELP = "<html><table border='1'>"
            + "<caption>在一次请求中，service_id与skill_ids两者可以组合使用，不同的组合关系所代表的语义如下表。</caption>"
            + "<tr><th>service_id</th><th>skill_ids</th><th>语义</th></tr>"
            + "<tr><td>有</td><td>有</td><td>调用从属于service_id所对应机器人中的某些技能。要求skill_ids中不可以包含不属于该机器人的技能。</td></tr>"
            + "<tr><td>有</td><td>无</td><td>调用从属于service_id所对应机器人中的所有技能。技能的顺序按照机器人所配置的顺序设定。</td></tr>"
            + "<tr><td>无</td><td>有</td><td>调用开发者名下的一系列技能，这些技能不一定从属于某个机器人。</td></tr>"
            + "<tr><td colspan='3'>注：机器人service_id，技能skill_ids。</td></tr>"
            + "</table></html>";
    private static final File CONFIG_FILE = new File("sc-digital-human.json");
    public static final int SAMPLE_RATE = 16000;
    public static final int SAMPLE_SIZE_BITS = 16;
    public static final int CHANNELS_NUMBER = 1;
    public static final int SPEAK_DURATION = 30;
    public static final String TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&&client_secret=%s";
    public static final String ASR_URL = "https://vop.baidu.com/pro_api?token=%s&cuid=SC1234567890&dev_pid=80001";
    public static final String TTS_URL = "https://tsn.baidu.com/text2audio?tex=%s&per=%s&aue=%s&tok=%s&cuid=SC1234567890&ctp=1&lan=zh";
    public static int APP_ID = 0;
    public static String APP_KEY = "", SECRET_KEY = "";
    public static String CHAT_VERSION = Chat.Ver.V2.toString();
    public static String SERVICE_ID = "";
    public static String[] SKILL_ID = null;
    public static String CHAT_APP_KEY = "", CHAT_SECRET_KEY = "";
    public static String CHAT_BOT_NAME = Chat.Bot.ERNIE_Speed_8K.toString();

    public static void readConfig() {
        System.err.println(CONFIG_FILE.getAbsolutePath());
        if (!CONFIG_FILE.exists()) {
            writeConfig();
        }
        try (Reader reader = new FileReader(CONFIG_FILE)) {
            JsonObject config = new Gson().fromJson(reader, JsonObject.class);
            if (config.has("APP_ID")) APP_ID = config.get("APP_ID").getAsInt();
            if (config.has("APP_KEY")) APP_KEY = config.get("APP_KEY").getAsString();
            if (config.has("SECRET_KEY")) SECRET_KEY = config.get("SECRET_KEY").getAsString();
            if (config.has("CHAT_VERSION")) CHAT_VERSION = config.get("CHAT_VERSION").getAsString();
            if (config.has("SERVICE_ID")) SERVICE_ID = config.get("SERVICE_ID").getAsString();
            if (config.has("SKILL_ID") && !config.get("SKILL_ID").isJsonNull())
                SKILL_ID = config.get("SKILL_ID").getAsString().split(",");
            if (config.has("CHAT_APP_KEY")) CHAT_APP_KEY = config.get("CHAT_APP_KEY").getAsString();
            if (config.has("CHAT_SECRET_KEY")) CHAT_SECRET_KEY = config.get("CHAT_SECRET_KEY").getAsString();
            if (config.has("CHAT_BOT_NAME")) CHAT_BOT_NAME = config.get("CHAT_BOT_NAME").getAsString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void writeConfig() {
        JsonObject config = new JsonObject();
        config.addProperty("APP_ID", APP_ID);
        config.addProperty("APP_KEY", APP_KEY);
        config.addProperty("SECRET_KEY", SECRET_KEY);
        config.addProperty("CHAT_VERSION", CHAT_VERSION);
        config.addProperty("SERVICE_ID", SERVICE_ID);
        config.addProperty("SKILL_ID", SKILL_ID == null || SKILL_ID.length == 0 ? null : String.join(",", SKILL_ID));
        config.addProperty("CHAT_APP_KEY", CHAT_APP_KEY);
        config.addProperty("CHAT_SECRET_KEY", CHAT_SECRET_KEY);
        config.addProperty("CHAT_BOT_NAME", CHAT_BOT_NAME);
        try (Writer writer = new FileWriter(CONFIG_FILE)) {
            new Gson().toJson(config, writer);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void readCmdlineArgs(String[] args) {
        APP_ID = getCmdline(args, "app.id", APP_ID);
        APP_KEY = getCmdline(args, "app.key", APP_KEY);
        SECRET_KEY = getCmdline(args, "secret.key", SECRET_KEY);
        CHAT_VERSION = getCmdline(args, "chat.version", CHAT_VERSION);
        SERVICE_ID = getCmdline(args, "service.id", SERVICE_ID);
        SKILL_ID = getCmdline(args, "skill.id", SKILL_ID);
        System.out.println("Usage: [--app.id=应用ＩＤ --app.key=应用ＡＫ --secret.key=应用ＳＫ --chat.version=服务版本" + Arrays.toString(Chat.Ver.values()) + "]");
        System.out.println("--app.id                      应用ＩＤ：" + APP_ID);
        System.out.println("--app.key                     应用ＡＫ：" + APP_KEY);
        System.out.println("--secret.key                  应用ＳＫ：" + SECRET_KEY);
        System.out.println("--chat.version                服务版本：" + CHAT_VERSION);
        System.out.println("--service.id                  服务ＩＤ：" + SERVICE_ID);
        System.out.println("--skill.id                    技能ＩＤ：" + Arrays.toString(SKILL_ID));
        CHAT_APP_KEY = getCmdline(args, "chat.app.key", CHAT_APP_KEY);
        CHAT_SECRET_KEY = getCmdline(args, "chat.secret.key", CHAT_SECRET_KEY);
        CHAT_BOT_NAME = getCmdline(args, "chat.bot.name", CHAT_BOT_NAME);
        System.out.println("Usage: [--chat.app.key=应用ＡＫ --chat.secret.key=应用ＳＫ --chat.bot.name=服务名称" + Arrays.toString(Chat.Bot.values()) + "]");
        System.out.println("--chat.app.key                应用ＡＫ：" + CHAT_APP_KEY);
        System.out.println("--chat.secret.key             应用ＳＫ：" + CHAT_SECRET_KEY);
        System.out.println("--chat.bot.name               服务名称：" + CHAT_BOT_NAME);
    }

    public static String getCmdline(String[] args, String key, String def) {
        String value = null;
        for (String arg : args) {
            if (arg.startsWith(String.format("--%s=", key))) {
                value = arg.substring(String.format("--%s=", key).length());
            } else if (arg.startsWith(String.format("-D%s=", key))) {
                value = arg.substring(String.format("-D%s=", key).length());
            }
        }
        return value == null || value.trim().isEmpty() ? def : value;
    }

    public static String[] getCmdline(String[] args, String key, String[] def) {
        String value = getCmdline(args, key, def == null || def.length == 0 ? null : String.join(",", def));
        return value == null || value.trim().isEmpty() ? null : value.split(",");
    }

    public static int getCmdline(String[] args, String key, int def) {
        return Integer.parseInt(getCmdline(args, key, String.valueOf(def)));
    }
}
